package com.testshiro.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

public class LoginFilter extends FormAuthenticationFilter {
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setHeader("Content-type",
				"application/json;charset=UTF-8");
		PrintWriter out;
		try {
			out = httpServletResponse.getWriter();
			out.println("{\"code\":-1,\"msg\":\"未登录用户！\"}");
			out.flush();
			out.close();
		} catch (IOException e1) {
			log.info(e1.getMessage());
		}
		return false;
	}

	@Override
	protected boolean onLoginFailure(AuthenticationToken token,
			AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setHeader("Content-type",
				"application/json;charset=UTF-8");
		PrintWriter out;
		try {
			out = httpServletResponse.getWriter();
			out.println("{\"code\":-1,\"msg\":\"系统错误\"}");
			out.flush();
			out.close();
		} catch (IOException e1) {
			log.info(e1.getMessage());
		}
		return false;
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		return super.onLoginSuccess(token, subject, request, response);
	}

	private final static Logger log = Logger.getLogger(LoginFilter.class);
}
